﻿using Newtonsoft.Json;
using Sustainalytics.OAuth.Services.Common;
using Sustainalytics.Portfolios.BL;
using Sustainalytics.Portfolios.Service.ErrorCodes;
using Sustainalytics.Portfolios.Service.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.Portfolios.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/exportPortfolioMatchedSecurity")]
    public class PortfolioMatchedSecuritiesExportController : ApiController
    {
        private readonly IPortfolioSecuritiesImportManagement _portfolioSecuritiesImportManager;

        private readonly PortfolioUserClaimsProcessor _userClaimsProcessor;

        public PortfolioMatchedSecuritiesExportController(
            IPortfolioSecuritiesImportManagement portfolioSecuritiesImportManager,
            PortfolioUserClaimsProcessor userClaimsProcessor)

        {
            _portfolioSecuritiesImportManager = portfolioSecuritiesImportManager;
            _userClaimsProcessor = userClaimsProcessor;
        }

        [Route("")]
        public HttpResponseMessage Post([FromBody] string exportDetailsMatches)
        {
            var exp = JsonConvert.DeserializeObject<ExportDetailsMatchesDto>(exportDetailsMatches);
            var userClaims = _userClaimsProcessor.GetPortfolioClaims();

            try
            {
                var multipartContent = new MultipartFormDataContent();

                var portfolioNameContent = new ObjectContent<string>(exp.PortfolioName, new JsonMediaTypeFormatter());
                multipartContent.Add(portfolioNameContent, "portfolioNameParam");

                byte[] processedFileContent = _portfolioSecuritiesImportManager.GetPortfolioSecurities(
                exp.PortfolioName,
                userClaims.AccountId,
                userClaims.UserId,
                userClaims.UserName,
                userClaims.UserFullName);

                var fileContent = new ByteArrayContent(processedFileContent);
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = exp.PortfolioName + "_Company_Match.xlsx"
                };

                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                // add the bytes to the multipart message
                multipartContent.Add(fileContent);

                var result = Request.CreateResponse(HttpStatusCode.OK);

                result.Content = multipartContent;
                return result;
            }
            catch (Exception e)
            {
                return this.Request.CreateResponse(
                    HttpStatusCode.InternalServerError,
                    new { ErrorCode = PortfoliosErrorCodes.PortfolioDetailsNotSaved });
            }
        }
    }
}
